package com.tomato.lock.common;

import lombok.AllArgsConstructor;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.text.MessageFormat.format;

@AllArgsConstructor
public class TryLockInterruptTest implements Runnable {
    static final Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new TryLockInterruptTest(), "tomato-thread-1");
        Thread t2 = new Thread(new TryLockInterruptTest(), "tomato-thread-2");
        t1.start();
        t2.start();
        Thread.sleep(1000);
        t2.interrupt();
    }

    @Override
    public void run() {
        try {
           if (lock.tryLock(5,TimeUnit.SECONDS)) {
               try {
                   System.out.println(MessageFormat.format("{0}获取锁成功" ,Thread.currentThread().getName()));
                  try {
                      Thread.sleep(5000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                      System.out.println(MessageFormat.format("{0}休眠期间被中断", Thread.currentThread().getName()));
                  }
               } finally {
                   lock.unlock();
               }
           }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(MessageFormat.format("{0}获取锁生了中断" ,Thread.currentThread().getName()));
        }


    }
}
